<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * App Channel Config Modal - 应用渠道配置模态框
 *
 * 功能：完全参考ChannelConfig.vue的模态框布局，实现应用级别的商户渠道配置
 * 版本：1.0.0
 * 参考：ChannelConfig.vue - 服务商渠道配置
 *
 * Website: https://www.anypay.com
-->

<template>
  <!-- 完全参考 ChannelConfig.vue 的模态框结构 -->
  <a-modal
    :open="visible"
    :title="`${appInfo?.appName || '应用'} - 商户渠道配置`"
    width="95%"
    :footer="null"
    @cancel="handleClose"
    @update:open="$emit('update:visible', $event)"
    class="app-channel-config-modal"
  >
    <div class="channel-config-workspace">
      <!-- 左侧：模式切换 + 渠道列表 -->
      <div class="channel-sidebar">
        <div class="sidebar-header">
          <h3>商户渠道配置</h3>
          <!-- 显示当前模式（由应用配置决定） -->
          <div class="mode-display">
            <span class="mode-label">当前模式：</span>
            <a-tag :color="currentMode === 'DIRECT' ? 'blue' : 'green'" size="small">
              {{ currentMode === 'DIRECT' ? '直连模式' : '服务商模式' }}
            </a-tag>
            <span class="mode-desc">（由应用配置决定）</span>
          </div>
        </div>

        <!-- 渠道列表 -->
        <div class="channel-list">
          <div
            v-for="template in channelTemplates"
            :key="template.channelId"
            class="channel-item"
            :class="{
              'active': state.selectedChannelId === template.channelId,
              'configured': template.isConfigured
            }"
            @click="handleChannelSelect(template.channelId)"
          >
            <div class="channel-item-content">
              <div class="channel-basic">
                <img
                  :src="getChannelIconUrlForTemplate(template)"
                  :alt="template.channelName"
                  class="channel-icon"
                  @error="handleTemplateImageError"
                />
                <div class="channel-info">
                  <div class="channel-name">{{ template.channelName }}</div>
                  <!--<div class="channel-code">{{ template.channelCode || '无渠道代码' }}</div>-->
                </div>
              </div>
                            <div class="channel-status">
                <div style="display: flex; flex-direction: column; gap: 4px; align-items: flex-end;">
                  <a-tag v-if="template.isConfigured" color="success" size="small">
                    已配置
                  </a-tag>
                  <a-tag v-else-if="getChannelStatus(template.channelCode) === 'PENDING'" color="warning" size="small">
                    待完善
                  </a-tag>
                  <!-- 协议类型标记 - 只显示兜底协议 -->
                  <a-tag
                    v-if="isDefaultProtocol(template.channelId)"
                    :color="getProtocolTypeColor(template.channelId)"
                    size="small"
                  >
                    {{ getProtocolTypeLabel(template.channelId) }}
                  </a-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：配置详情 - 参考 ChannelConfig 的详情面板 -->
      <div class="channel-detail">
        <div v-if="state.loading && !state.initialized" class="loading-state">
          <a-skeleton active :paragraph="{ rows: 8 }" />
        </div>

        <div v-else-if="!state.selectedChannelId" class="empty-state">
          <a-empty description="请选择要配置的渠道" />
        </div>

        <div v-else class="channel-detail-content">
          <div class="detail-header">
            <div class="channel-title">
              <img
                :src="getChannelIconUrl()"
                :alt="selectedChannelTemplate?.channelName || '渠道图标'"
                class="channel-icon"
                @error="handleImageError"
              />
              <div>
                <h3>{{ selectedChannelTemplate?.channelName || '未知渠道' }}</h3>
                <p class="channel-desc">{{ currentMode === 'DIRECT' ? '商户直连配置' : '子商户渠道配置' }}</p>
              </div>
            </div>

            <div class="detail-actions">
              <!-- 控制开关组 - 参考 ChannelConfig -->
              <div style="display: flex; gap: 16px; align-items: center;">
                <!-- 启用状态开关 -->
                <div class="channel-status-control" style="display: flex; align-items: center;">
                  <span style="color: #666; font-size: 13px; margin-right: 8px;">启用状态：</span>
                  <a-switch
                    v-model:checked="selectedChannelConfig.enabled"
                    @change="handleChannelToggle(state.selectedChannelId, $event)"
                    size="small"
                  />
                  <span style="color: #666; font-size: 12px; margin-left: 8px;">
                    {{ selectedChannelConfig.enabled ? '已启用' : '已禁用' }}
                  </span>
                </div>

                <!-- 测试和保存按钮 -->
                <a-space>
                  <a-button
                    v-if="currentConfig"
                    type="default"
                    :loading="state.testLoading"
                    @click="handleTestConnection"
                  >
                    <ExperimentOutlined />
                    测试连接
                  </a-button>
                </a-space>
              </div>
            </div>
          </div>

          <!-- 配置表单容器 - 参考 ChannelConfig 的动态Tab界面 -->
          <div class="config-form-container">
            <!-- 当前协议信息显示 - 参考服务商渠道配置界面 -->
            <div style="margin-bottom: 16px; padding: 12px 16px; background: #fafafa; border: 1px solid #e8e8e8; border-radius: 6px;">
              <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                <span style="color: #666; font-size: 13px;">📋 当前配置类型：</span>
                <span style="color: #1890ff; font-weight: 500; font-size: 13px;">
                  {{ currentMode === 'DIRECT' ? '商户直连配置' : '子商户渠道配置' }}
                </span>
                <span
                  style="color: #52c41a; font-size: 12px; background: #f6ffed; padding: 2px 6px; border-radius: 4px; border: 1px solid #b7eb8f;"
                >
                  {{ selectedChannelTemplate?.channelName }}
                </span>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="color: #666; font-size: 13px;">🔧 当前协议：</span>
                <span style="color: #722ed1; font-weight: 500; font-size: 13px;">
                  {{ getCurrentProtocolId() }}
                </span>
                <span style="color: #fa8c16; font-size: 12px;">v{{ getCurrentProtocolVersion() }}</span>
                <span style="color: #999; font-size: 12px;">{{ getCurrentProtocolName() }}</span>
              </div>
            </div>

            <!-- 动态协议表单渲染 - 使用Tab结构 -->
            <a-tabs v-model:activeKey="state.configActiveTab" type="card">
              <!-- 动态渲染协议定义的Tab -->
              <a-tab-pane
                v-for="section in configSections"
                :key="section.key"
                :tab="section.tab"
              >
                <a-form layout="vertical" :model="selectedChannelConfig">
                  <!-- 渲染该分区的字段 -->
                  <a-card :title="section.tab" size="small" style="margin-bottom: 16px;">
                    <a-row :gutter="16">
                      <a-col
                        v-for="field in section.fields"
                        :key="field.fieldKey"
                        :span="getFieldSpan(field.fieldType)"
                      >
                        <a-form-item
                          :label="field.fieldName"
                          :required="field.required"
                          :help="field.description || field.placeholder"
                        >
                          <!-- 输入框 -->
                          <a-input
                            v-if="field.fieldType === 'INPUT'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          />
                          <!-- 密码框 -->
                          <a-input-password
                            v-else-if="field.fieldType === 'PASSWORD'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          />
                          <!-- 选择框 -->
                          <a-select
                            v-else-if="field.fieldType === 'SELECT'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            :mode="field.multiple ? 'multiple' : undefined"
                          >
                            <a-select-option
                              v-for="option in field.options"
                              :key="option.value"
                              :value="option.value"
                            >
                              {{ option.label }}
                            </a-select-option>
                          </a-select>
                          <!-- 文本域 -->
                          <a-textarea
                            v-else-if="field.fieldType === 'TEXTAREA'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            :rows="4"
                          />
                          <!-- 开关 -->
                          <a-switch
                            v-else-if="field.fieldType === 'SWITCH'"
                            :checked="getFieldValue(field.fieldKey, section.key)"
                            @update:checked="setFieldValue(field.fieldKey, section.key, $event)"
                          />
                          <!-- 数字输入框 -->
                          <a-input-number
                            v-else-if="field.fieldType === 'NUMBER'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            style="width: 100%"
                          />
                          <!-- 单选按钮组 -->
                          <a-radio-group
                            v-else-if="field.fieldType === 'RADIO'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                          >
                            <a-radio
                              v-for="option in field.options"
                              :key="option.value"
                              :value="option.value"
                              :disabled="option.disabled"
                            >
                              {{ option.label }}
                            </a-radio>
                          </a-radio-group>
                          <!-- URL输入框 -->
                          <a-input
                            v-else-if="field.fieldType === 'URL'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            type="url"
                          />
                          <!-- 文件上传 -->
                          <a-upload
                            v-else-if="field.fieldType === 'UPLOAD'"
                            :file-list="[]"
                            @change="handleFileUpload(field.fieldKey, section.key, $event)"
                          >
                            <a-button>
                              <template #icon><UploadOutlined /></template>
                              选择文件
                            </a-button>
                          </a-upload>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-form>
              </a-tab-pane>
            </a-tabs>
          </div>

          <!-- 固定保存按钮 - 参考 ChannelConfig -->
          <div class="fixed-save-button">
            <a-button
              type="primary"
              size="large"
              @click="handleSaveChannelConfig(state.selectedChannelId)"
              :loading="state.savingChannels.includes(state.selectedChannelId)"
            >
              <template #icon>
                <SaveOutlined />
              </template>
              保存配置
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, computed, watch, getCurrentInstance, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import {
  ApiOutlined,
  TeamOutlined,
  ExperimentOutlined,
  SaveOutlined,
  UploadOutlined
} from '@ant-design/icons-vue'
import { paymentChannels } from '@/mock/channels'
import { appConfigs, type ChannelMerchantConfig } from '@/mock/appconfigs'
import { protocol3Manager } from '@/mock/protocol3-manager'
import { initializeSampleData } from '@/mock/protocol3-sample-data'
import type { MerchantChannelConfig3, QRCodeConfig } from '@/types/protocol3-types'
// 临时接口定义
interface AppChannelConfig {
  id: string
  appId: string
  merchantId: string
  channelCode: string
  connectMode: 'DIRECT' | 'INDIRECT'
  providerId?: string
  enabled: boolean
  configData: Record<string, any>
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING'
  lastTestTime?: string
  lastTestResult?: 'SUCCESS' | 'FAILED'
  createdTime: string
  updatedTime: string
}

// 从 appconfigs.ts 中获取真实数据的函数
const getAppChannelConfigsFromAppConfigs = (appId: string): AppChannelConfig[] => {
  const appConfig = appConfigs.find(app => app.appId === appId)
  if (!appConfig || !appConfig.channelMerchantConfigs) {
    return []
  }

  return Object.entries(appConfig.channelMerchantConfigs).map(([channelCode, config]) => ({
    id: `${appId}_${channelCode}`,
    appId: appId,
    merchantId: appConfig.merchantId,
    channelCode: channelCode,
    connectMode: config.connectMode,
    enabled: config.enabled,
    configData: config.configData,
    status: config.status,
    createdTime: config.lastUpdateTime,
    updatedTime: config.lastUpdateTime
  }))
}

const mockGetAppChannelConfigs = (appId: string) => {
  const configs = getAppChannelConfigsFromAppConfigs(appId)
  return Promise.resolve({ data: configs })
}

const mockGetAppChannelConfig = (appId: string, channelCode: string, connectMode: string) => {
  const configs = getAppChannelConfigsFromAppConfigs(appId)
  const config = configs.find(c => c.channelCode === channelCode && c.connectMode === connectMode)
  return Promise.resolve({ data: config || null })
}

const mockSaveAppChannelConfig = (config: Partial<AppChannelConfig>) => {
  // 这里可以添加保存到 appconfigs 的逻辑
  console.log('保存配置:', config)
  return Promise.resolve({ success: true, message: '保存成功' })
}

const mockTestAppChannelConfig = (appId: string, channelCode: string, connectMode: string) => {
  return Promise.resolve({ success: true, message: '连接测试成功' })
}
import type { ConfigSection } from '@/types/channel-config-protocol'

// Props
interface Props {
  visible: boolean
  appInfo?: {
    appId: string
    appName: string
    merchantId: string
    connectMode?: string
  }
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  appInfo: () => ({ appId: '', appName: '', merchantId: '', connectMode: 'DIRECT' })
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': []
}>()

// 获取全局消息提示
const { $AnyMessageBox } = getCurrentInstance()!.appContext.config.globalProperties

// 响应式数据 - 采用更清晰的状态管理
const currentMode = computed(() => {
  // 从应用配置中获取connectMode，INDIRECT保持INDIRECT，DIRECT保持不变
  const appConnectMode = props.appInfo?.connectMode || 'DIRECT'
  return appConnectMode === 'INDIRECT' ? 'INDIRECT' : 'DIRECT'
})

// 核心状态 - 统一的响应式状态管理
const state = reactive({
  channelConfigs: [] as AppChannelConfig[],
  selectedChannelId: '',
  configActiveTab: '',
  loading: false,
  initialized: false,
  protocol3Ready: false,
  testLoading: false,
  savingChannels: [] as string[]
})

// 渠道代码映射：从完整的渠道代码映射到协议管理器使用的简化代码
const channelCodeMapping: Record<string, string> = {
  'CHANNEL_IF_WXPAY': 'WXPAY',
  'CHANNEL_IF_ALIPAY': 'ALIPAY',
  'CHANNEL_IF_HUIFU': 'HUIFU',
  'CHANNEL_IF_DOUGONG': 'DOUGONG',
  'CHANNEL_IF_FUIOU': 'FUIOU',
  'CHANNEL_IF_LAKALA': 'LAKALA',
  'CHANNEL_IF_LESHUA': 'LESHUA',
  'CHANNEL_IF_UNIONPAY': 'UNIONPAY',
  'CHANNEL_IF_YEEPAY': 'YEEPAY',
  'CHANNEL_IF_PAYPAL': 'PAYPAL'
}

// 计算属性 - 参考 ChannelConfig.vue 的结构
const channelTemplates = computed(() => {
  // 根据模式过滤支付渠道
  const modeChannels = paymentChannels.filter(channel => {
    if (currentMode.value === 'DIRECT') {
      return channel.supportDirect
    } else {
      return channel.supportProvider
    }
  })

  // 映射渠道并添加配置状态信息
  const mappedChannels = modeChannels.map(channel => {
    const simpleChannelCode = channelCodeMapping[channel.channelCode] || channel.channelCode

    // 检查该渠道是否已配置
    const isConfigured = state.channelConfigs.some(config =>
      config.channelCode === channel.channelCode &&
      config.connectMode === currentMode.value &&
      config.enabled
    )

    return {
      ...channel,
      channelId: simpleChannelCode, // 使用简化的渠道代码作为ID
      simpleChannelCode, // 添加简化代码字段
      isConfigured, // 是否已配置
      description: `${channel.channelName}${currentMode.value === 'DIRECT' ? '商户直连' : '子商户'}配置`
    }
  })

  // 排序：已配置的渠道优先，其次是私有协议，然后按渠道名称排序
  return mappedChannels.sort((a, b) => {
    // 首先按配置状态排序：已配置的在前
    if (a.isConfigured && !b.isConfigured) return -1
    if (!a.isConfigured && b.isConfigured) return 1

    // 然后按协议类型排序：私有协议优先于默认协议
    const aIsDefaultProtocol = isDefaultProtocol(a.channelId)
    const bIsDefaultProtocol = isDefaultProtocol(b.channelId)
    if (!aIsDefaultProtocol && bIsDefaultProtocol) return -1
    if (aIsDefaultProtocol && !bIsDefaultProtocol) return 1

    // 最后按渠道名称排序
    return a.channelName.localeCompare(b.channelName)
  })
})

// 选中的渠道模板 - 参考 ChannelConfig.vue
const selectedChannelTemplate = computed(() => {
  return channelTemplates.value.find(t => t.channelId === state.selectedChannelId)
})

// 选中渠道的配置 - 参考 ChannelConfig.vue
const selectedChannelConfig = computed(() => {
  return getChannelConfig(state.selectedChannelId)
})

// 当前配置对象
const currentConfig = computed(() => {
  if (!state.selectedChannelId) return null
  const fullChannelCode = getFullChannelCode(state.selectedChannelId)
  return state.channelConfigs.find(
    c => c.channelCode === fullChannelCode && c.connectMode === currentMode.value
  )
})

// 获取渠道协议 - 使用protocol3Manager方式
const selectedChannelProtocol = computed(() => {
  if (!state.selectedChannelId || !state.protocol3Ready) return null

  try {
    // 使用protocol3Manager根据约定获取协议
    const fullChannelCode = getFullChannelCode(state.selectedChannelId)
    const protocolCode = fullChannelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')

    // 根据模式确定配置类型
    const configType = currentMode.value === 'DIRECT' ? 'DIRECT_MERCHANT' : 'SUB_MERCHANT'
    const protocolId = protocol3Manager.getProtocolByConvention(protocolCode, configType)

    if (protocolId) {
      const protocol = protocol3Manager.getProtocol(protocolId)
      return protocol
    }

    return null
  } catch (error) {
    console.warn('获取渠道协议失败:', error)
    return null
  }
})

// 当前协议对象（兼容性别名）
const currentProtocol = computed(() => selectedChannelProtocol.value)

// 当前协议的配置分区 - 使用Protocol3，增加更严格的状态检查
const configSections = computed(() => {
  // 必须满足所有条件才能渲染配置分区
  if (!state.selectedChannelId || !state.initialized || !state.protocol3Ready) {
    return []
  }

  const protocol = selectedChannelProtocol.value
  if (!protocol?.configSections?.length) {
    console.log('[配置分区] 协议或配置分区不可用:', {
      hasSelectedChannel: !!state.selectedChannelId,
      hasProtocol: !!protocol,
      hasConfigSections: !!protocol?.configSections?.length,
      initialized: state.initialized,
      protocol3Ready: state.protocol3Ready
    })
    return []
  }

  const sections = protocol.configSections.map((section: any) => ({
    key: section.sectionKey,
    tab: section.sectionName,
    icon: section.icon,
    description: section.description,
    fields: section.fields,
    order: section.order || 0,
    collapsed: section.collapsed || false
  })).sort((a: any, b: any) => a.order - b.order)

  console.log(`[配置分区] 渠道: ${state.selectedChannelId}, 协议: ${protocol.protocolId}, 分区数量: ${sections.length}`)
  return sections
})

// 参考 ChannelConfig.vue 的配置获取逻辑
const getChannelConfig = (channelCode: string): any => {
  // 将简化的渠道代码映射回完整的渠道代码
  const fullChannelCode = getFullChannelCode(channelCode)

  console.log(`[getChannelConfig] 渠道代码: ${channelCode} -> ${fullChannelCode}`)
  console.log(`[getChannelConfig] 当前模式: ${currentMode.value}`)
  console.log(`[getChannelConfig] 当前配置列表:`, state.channelConfigs.map(c => ({ channelCode: c.channelCode, connectMode: c.connectMode })))

  let config = state.channelConfigs.find(c =>
    c.channelCode === fullChannelCode && c.connectMode === currentMode.value
  )

  if (!config) {
    console.log(`[getChannelConfig] 在 channelConfigs 中未找到配置，尝试从 appconfigs.ts 获取`)
    // 如果没有找到配置，尝试从 appconfigs.ts 中直接获取
    const appConfig = appConfigs.find(app => app.appId === props.appInfo?.appId)
    console.log(`[getChannelConfig] 找到应用配置:`, appConfig?.appId)
    console.log(`[getChannelConfig] 应用配置中的渠道商户配置:`, appConfig?.channelMerchantConfigs)

    if (appConfig?.channelMerchantConfigs?.[fullChannelCode]) {
      const existingConfig = appConfig.channelMerchantConfigs[fullChannelCode]
      console.log(`[getChannelConfig] 找到现有配置:`, existingConfig)

      config = {
        id: `${props.appInfo?.appId}_${fullChannelCode}`,
        appId: props.appInfo?.appId || '',
        merchantId: props.appInfo?.merchantId || '',
        channelCode: fullChannelCode,
        connectMode: existingConfig.connectMode,
        enabled: existingConfig.enabled,
        configData: existingConfig.configData,
        status: existingConfig.status,
        createdTime: existingConfig.lastUpdateTime,
        updatedTime: existingConfig.lastUpdateTime
      }
      // 将找到的配置添加到 channelConfigs 中
      state.channelConfigs.push(config)
      console.log(`[getChannelConfig] 已添加配置到 channelConfigs:`, config)
    } else {
      console.log(`[getChannelConfig] 在 appconfigs.ts 中也未找到配置，创建默认配置`)
      // 如果还是没有找到，才创建默认配置对象
    config = {
      id: '',
      appId: props.appInfo?.appId || '',
      merchantId: props.appInfo?.merchantId || '',
        channelCode: fullChannelCode,
      connectMode: currentMode.value,
      enabled: false,
      configData: generateDefaultConfigData(channelCode, currentMode.value),
      status: 'INACTIVE',
      createdTime: new Date().toLocaleString(),
      updatedTime: new Date().toLocaleString()
    }
    }
  } else {
    console.log(`[getChannelConfig] 在 channelConfigs 中找到配置:`, config)
  }

  console.log(`[getChannelConfig] 最终返回的配置:`, config)
  return config
}

// Protocol3 相关计算属性和方法

// 获取当前协议 ID - 使用protocol3Manager方式
const currentProtocolId = computed(() => {
  if (!state.selectedChannelId) return '未知协议'

  try {
    const fullChannelCode = getFullChannelCode(state.selectedChannelId)
    const protocolCode = fullChannelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')
    const configType = currentMode.value === 'DIRECT' ? 'DIRECT_MERCHANT' : 'SUB_MERCHANT'
    const protocolId = protocol3Manager.getProtocolByConvention(protocolCode, configType)

    return protocolId || 'DEFAULT_PROTOCOL_FALLBACK_001'
  } catch (error) {
    console.warn('获取协议 ID失败:', error)
    return 'DEFAULT_PROTOCOL_FALLBACK_001'
  }
})

// 获取协议信息（包括是否为默认协议）- 使用protocol3Manager方式
const protocolInfo = computed(() => {
  if (!state.selectedChannelId) return null

  try {
    const fullChannelCode = getFullChannelCode(state.selectedChannelId)
    const protocolCode = fullChannelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')
    const configType = currentMode.value === 'DIRECT' ? 'DIRECT_MERCHANT' : 'SUB_MERCHANT'
    const protocolId = protocol3Manager.getProtocolByConvention(protocolCode, configType)

    if (protocolId) {
      const protocol = protocol3Manager.getProtocol(protocolId)

      return {
        protocol: protocol,
        protocolId: protocolId,
        isDefault: protocolId === 'DEFAULT_PROTOCOL_FALLBACK_001',
        source: protocolId === 'DEFAULT_PROTOCOL_FALLBACK_001' ? 'fallback' : 'protocol3'
      }
    }

    return null
  } catch (error) {
    console.warn('获取协议信息失败:', error)
    return null
  }
})

const getFieldSpan = (fieldType: string): number => {
  // 支持更多 Protocol3 字段类型
  const fullWidthFields = ['textarea', 'TEXTAREA', 'upload', 'UPLOAD']
  return fullWidthFields.includes(fieldType) ? 24 : 12
}

const isChannelConfigured = (channelCode: string): boolean => {
  const fullChannelCode = getFullChannelCode(channelCode)
  return state.channelConfigs.some(
    config => config.channelCode === fullChannelCode && config.connectMode === currentMode.value
  )
}

const getChannelStatus = (channelCode: string): string => {
  const fullChannelCode = getFullChannelCode(channelCode)
  const config = state.channelConfigs.find(
    c => c.channelCode === fullChannelCode && c.connectMode === currentMode.value
  )
  return config?.status || 'INACTIVE'
}

// 方法
const handleClose = () => {
  emit('update:visible', false)
  resetState()
}

// handleModeChange方法已删除，因为现在使用应用配置的connectMode

// 统一的状态管理函数
const updateChannelState = (channelId: string) => {
  state.selectedChannelId = channelId

  // 同步更新活动tab（基于当前可用的配置分区）
  const sections = configSections.value
  if (sections.length > 0) {
    state.configActiveTab = sections[0].key
    console.log(`[状态更新] 渠道: ${channelId}, 设置活动tab: ${state.configActiveTab}`)
  } else {
    state.configActiveTab = ''
    console.log(`[状态更新] 渠道: ${channelId}, 清空活动tab (无配置分区)`)
  }
}

const handleChannelSelect = (channelId: string) => {
  console.log(`[渠道选择] 选择渠道: ${channelId}`)
  updateChannelState(channelId)
}

// 添加调试方法，打印渠道排序信息
const debugChannelSorting = () => {
  console.log('=== 渠道排序调试信息 ===')
  console.log('当前渠道配置列表:', state.channelConfigs.map(c => ({
    channelCode: c.channelCode,
    connectMode: c.connectMode,
    enabled: c.enabled
  })))

  console.log('排序后的渠道模板:', channelTemplates.value.map(t => ({
    channelName: t.channelName,
    channelCode: t.channelCode,
    isConfigured: t.isConfigured,
    channelId: t.channelId
  })))
  console.log('=== 渠道排序调试信息结束 ===')
}

const handleChannelToggle = (channelId: string, enabled: boolean) => {
  const config = getChannelConfig(channelId)
  config.enabled = enabled
  config.status = enabled ? 'ACTIVE' : 'INACTIVE'
  config.updatedTime = new Date().toLocaleString()

  // 如果启用了渠道且当前没有选中任何渠道，则选中这个渠道
  if (enabled && !state.selectedChannelId) {
    updateChannelState(channelId)
  }
}

// 参考 ChannelConfig.vue 的保存逻辑
const handleSaveChannelConfig = async (channelId: string) => {
  if (!props.appInfo?.appId) return

  // 验证配置数据
  const config = getChannelConfig(channelId)
  const validation = validateAppChannelConfigData(
    channelId,
    currentMode.value,
    config.configData
  )

  if (!validation.valid) {
    message.error('配置验证失败：' + validation.errors.join('，'))
    return
  }

  state.savingChannels.push(channelId)
  try {
    config.id = config.id || `ACC${Date.now()}`
    config.updatedTime = new Date().toLocaleString()
    config.status = 'ACTIVE'

    const response = await mockSaveAppChannelConfig(config)
    if (response.success) {
      message.success('保存配置成功')
      emit('success')

      // 重新加载数据
      await loadAppChannelConfigs()
    }
  } catch (error) {
    message.error('保存配置失败')
  } finally {
    state.savingChannels = state.savingChannels.filter(id => id !== channelId)
  }
}

const handleTestConnection = async () => {
  if (!state.selectedChannelId || !currentConfig.value) {
    message.warning('请先保存配置后再测试')
    return
  }

  state.testLoading = true
  try {
    const response = await mockTestAppChannelConfig(
      props.appInfo?.appId || '',
      state.selectedChannelId,
      currentMode.value
    )

    if (response.success) {
      message.success('连接测试成功')
    } else {
      message.error(response.message)
    }

    // 重新加载当前配置以更新测试结果
    await loadAppChannelConfigs()
  } catch (error) {
    message.error('连接测试失败')
  } finally {
    state.testLoading = false
  }
}

const loadAppChannelConfigs = async () => {
  if (!props.appInfo?.appId) return

  state.loading = true
  try {
    const response = await mockGetAppChannelConfigs(props.appInfo.appId)
    state.channelConfigs = response.data

    // 自动选择第一个可用渠道
    if (!state.selectedChannelId && channelTemplates.value.length > 0) {
      const firstChannelId = channelTemplates.value[0]?.channelId || ''
      console.log(`[加载配置] 自动选择第一个渠道: ${firstChannelId}`)
      updateChannelState(firstChannelId)
    }

    state.initialized = true
    debugChannelSorting()
  } catch (error) {
    message.error('加载渠道配置失败')
  } finally {
    state.loading = false
  }
}

// Protocol3 数据初始化
const initializeProtocol3Data = async () => {
  try {
    console.log('[初始化] 开始初始化Protocol3数据...')
    await initializeSampleData()
    state.protocol3Ready = true
    console.log('[初始化] Protocol3数据初始化完成')
  } catch (error) {
    console.error('[初始化] Protocol3数据初始化失败:', error)
    throw error
  }
}

// 完整的初始化流程
const initializeModal = async () => {
  if (!props.appInfo?.appId || state.initialized) return

  state.loading = true
  try {
    // 1. 初始化Protocol3数据
    await initializeProtocol3Data()

    // 2. 加载渠道配置
    await loadAppChannelConfigs()

    console.log('[初始化] 模态框初始化完成')
  } catch (error) {
    console.error('[初始化] 模态框初始化失败:', error)
    message.error('初始化失败: ' + (error as Error).message)
  } finally {
    state.loading = false
  }
}

// 重置状态
const resetState = () => {
  Object.assign(state, {
    channelConfigs: [],
    selectedChannelId: '',
    configActiveTab: '',
    loading: false,
    initialized: false,
    protocol3Ready: false,
    testLoading: false,
    savingChannels: []
  })
}

// 监听visible变化
watch(
  () => props.visible,
  async (visible) => {
    if (visible) {
      await initializeModal()
    } else {
      resetState()
    }
  }
)

// 生成默认配置数据（基于协议）
const generateDefaultConfigData = (channelCode: string, connectMode: string): Record<string, any> => {
  try {
    // 使用完整的渠道代码
    const fullChannelCode = getFullChannelCode(channelCode)
    let protocol

    // 使用Protocol3正确的协议获取方式
    const protocolCode = fullChannelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')
    const configType = connectMode === 'DIRECT' ? 'DIRECT_MERCHANT' : 'SUB_MERCHANT'
    const protocolId = protocol3Manager.getProtocolByConvention(protocolCode, configType)
    protocol = protocol3Manager.getProtocol(protocolId)

    const defaultData: Record<string, any> = {}

    // 从协议的配置分区中生成分区结构
    protocol.configSections?.forEach(section => {
      const sectionData: Record<string, any> = {}

      // 从分区的默认值中提取
      if (section.defaultValues) {
        Object.assign(sectionData, section.defaultValues)
      }

      // 从字段中提取默认值
      section.fields?.forEach(field => {
        if (field.defaultValue !== undefined) {
          sectionData[field.fieldKey] = field.defaultValue
        }
      })

      // 将分区数据添加到根对象
      defaultData[section.sectionKey] = sectionData
    })

    console.log(`[generateDefaultConfigData] 生成的默认配置数据:`, defaultData)
    return defaultData
  } catch (error) {
    console.warn('生成默认配置数据失败:', error)
    return {}
  }
}

// 验证配置数据（基于协议）
const validateAppChannelConfigData = (channelCode: string, connectMode: string, configData: Record<string, any>) => {
  const validation = {
    valid: true,
    errors: [] as string[]
  }

  try {
    // 使用完整的渠道代码
    const fullChannelCode = getFullChannelCode(channelCode)
    let protocol

    // 使用Protocol3正确的协议获取方式
    const protocolCode = fullChannelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')
    const configType = connectMode === 'DIRECT' ? 'DIRECT_MERCHANT' : 'SUB_MERCHANT'
    const protocolId = protocol3Manager.getProtocolByConvention(protocolCode, configType)
    protocol = protocol3Manager.getProtocol(protocolId)

    // 验证所有配置分区的字段
    protocol.configSections?.forEach(section => {
      section.fields?.forEach(field => {
        // 从分区结构中获取字段值
        let value
        if (configData[section.sectionKey] && configData[section.sectionKey][field.fieldKey] !== undefined) {
          value = configData[section.sectionKey][field.fieldKey]
        } else if (configData[field.fieldKey] !== undefined) {
          // 兼容旧格式
          value = configData[field.fieldKey]
        }

        // 检查必填字段
        if (field.required && (!value || value === '')) {
          validation.valid = false
          validation.errors.push(`${field.fieldName}不能为空`)
        }

        // 检查字段验证规则
        if (value && field.validation) {
          const fieldValidation = field.validation

          // 检查正则表达式
          if (fieldValidation.pattern && !new RegExp(fieldValidation.pattern).test(value)) {
            validation.valid = false
            validation.errors.push(fieldValidation.message || `${field.fieldName}格式不正确`)
          }

          // 检查长度限制
          if (fieldValidation.minLength && value.length < fieldValidation.minLength) {
            validation.valid = false
            validation.errors.push(`${field.fieldName}长度不能少于${fieldValidation.minLength}位`)
          }

          if (fieldValidation.maxLength && value.length > fieldValidation.maxLength) {
            validation.valid = false
            validation.errors.push(`${field.fieldName}长度不能超过${fieldValidation.maxLength}位`)
          }

          // 检查数值范围
          if (typeof value === 'number') {
            if (fieldValidation.min !== undefined && value < fieldValidation.min) {
              validation.valid = false
              validation.errors.push(`${field.fieldName}不能小于${fieldValidation.min}`)
            }

            if (fieldValidation.max !== undefined && value > fieldValidation.max) {
              validation.valid = false
              validation.errors.push(`${field.fieldName}不能大于${fieldValidation.max}`)
            }
          }
        }
      })
    })
  } catch (error) {
    console.warn('验证配置数据失败:', error)
    validation.valid = false
    validation.errors.push('配置验证失败')
  }

  return validation
}

// 获取完整的渠道代码（从简化代码映射回完整代码）
const getFullChannelCode = (simpleChannelCode: string): string => {
  // 反向查找映射关系
  for (const [fullCode, simpleCode] of Object.entries(channelCodeMapping)) {
    if (simpleCode === simpleChannelCode) {
      return fullCode
    }
  }
  // 如果找不到映射，返回原始代码
  return simpleChannelCode
}

// 获取当前选中渠道的协议ID - 使用Protocol3
const getCurrentProtocolId = () => {
  return currentProtocolId.value
}

// 获取当前选中渠道的协议名称 - 使用Protocol3
const getCurrentProtocolName = () => {
  const protocol = selectedChannelProtocol.value
  return protocol?.name || '未知协议名称'
}

// 获取当前选中渠道的协议版本 - 使用Protocol3
const getCurrentProtocolVersion = () => {
  const protocol = selectedChannelProtocol.value
  return protocol?.version || '1.0.0'
}

// 检查是否为默认协议的方法
const isDefaultProtocol = (channelId: string): boolean => {
  try {
    const fullChannelCode = getFullChannelCode(channelId)
    const protocolCode = fullChannelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')
    const configType = currentMode.value === 'DIRECT' ? 'DIRECT_MERCHANT' : 'SUB_MERCHANT'
    const protocolId = protocol3Manager.getProtocolByConvention(protocolCode, configType)
    return protocolId === 'DEFAULT_PROTOCOL_FALLBACK_001'
  } catch (error) {
    return true // 如果出错，假设使用默认协议
  }
}

// 获取协议类型颜色
const getProtocolTypeColor = (channelId: string): string => {
  return isDefaultProtocol(channelId) ? 'orange' : 'green'
}

// 获取协议类型标签
const getProtocolTypeLabel = (channelId: string): string => {
  return isDefaultProtocol(channelId) ? '兜底协议' : '私有协议'
}

// 获取字段值（支持分区结构）
const getFieldValue = (fieldKey: string, sectionKey: string) => {
  const config = selectedChannelConfig.value
  if (!config || !config.configData) return ''

  // 优先从分区结构中获取
  if (config.configData[sectionKey] && config.configData[sectionKey][fieldKey] !== undefined) {
    return config.configData[sectionKey][fieldKey]
  }

  // 兼容旧格式：直接从根级别获取
  if (config.configData[fieldKey] !== undefined) {
    return config.configData[fieldKey]
  }

  return ''
}

// 设置字段值（支持分区结构）
const setFieldValue = (fieldKey: string, sectionKey: string, value: any) => {
  const config = selectedChannelConfig.value
  if (!config || !config.configData) return

  // 确保分区结构存在
  if (!config.configData[sectionKey]) {
    config.configData[sectionKey] = {}
  }

  // 设置分区中的字段值
  config.configData[sectionKey][fieldKey] = value

  // console.log(`[setFieldValue] 设置字段: ${sectionKey}.${fieldKey} = ${value}`)
  // console.log(`[setFieldValue] 当前配置数据:`, config.configData)
}

// 获取渠道图标URL
const getChannelIconUrl = () => {
  if (!selectedChannelTemplate.value) {
    return '/icons/default-channel.png'
  }

  // 优先使用模板中的图标URL
  if (selectedChannelTemplate.value.iconUrl) {
    return selectedChannelTemplate.value.iconUrl
  }

  // 如果没有图标URL，尝试根据渠道代码生成默认图标路径
  const channelCode = selectedChannelTemplate.value.channelCode?.toLowerCase()
  if (channelCode) {
    return `/icons/${channelCode}.png`
  }

  return '/icons/default-channel.png'
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.warn(`[图片加载失败] 渠道: ${selectedChannelTemplate.value?.channelName}, 路径: ${img.src}`)
  img.src = '/icons/default-channel.png'
}

// 处理文件上传
const handleFileUpload = (fieldKey: string, sectionKey: string, info: any) => {
  if (info.file.status === 'done') {
    setFieldValue(fieldKey, sectionKey, info.file.response?.url || info.file.name)
    message.success('文件上传成功')
  } else if (info.file.status === 'error') {
    message.error('文件上传失败')
  }
}


// 监听配置分区变化，自动修正活动tab
watch([configSections], (newSections) => {
  // 如果当前活动tab不在新的分区列表中，则重新设置
  if (newSections.length > 0) {
    const currentTabExists = newSections.some(section => section.key === state.configActiveTab)
    if (!currentTabExists) {
      state.configActiveTab = newSections[0].key
      console.log(`[配置分区监听] 修正活动tab: ${state.configActiveTab}`)
    }
  } else {
    state.configActiveTab = ''
  }
}, { immediate: true })

// 获取模板渠道图标URL
const getChannelIconUrlForTemplate = (template: any) => {
  // 优先使用模板中的图标URL
  if (template.iconUrl) {
    return template.iconUrl
  }

  // 如果没有图标URL，尝试根据渠道代码生成默认图标路径
  const channelCode = template.channelCode?.toLowerCase()
  if (channelCode) {
    return `/icons/${channelCode}.png`
  }

  return '/icons/default-channel.png'
}

// 处理模板图片加载错误
const handleTemplateImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.warn(`[模板图片加载失败] 路径: ${img.src}`)
  img.src = '/icons/default-channel.png'
}



</script>

<style scoped>
/* 参考 ChannelConfig.vue 的样式结构 */
.app-channel-config-modal :deep(.ant-modal-body) {
  padding: 0;
}

.channel-config-workspace {
  display: flex;
  height: 92vh;
  min-height: 800px;
  max-height: 1000px;
}

.channel-sidebar {
  width: 320px;
  border-right: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
}

.sidebar-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
}

.mode-display {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.mode-label {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.mode-desc {
  font-size: 12px;
  color: #999;
}

.channel-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.channel-item {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.channel-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.channel-item.active {
  border-color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.channel-item.configured {
  border-left: 4px solid #52c41a;
}

.channel-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.channel-basic {
  display: flex;
  align-items: center;
  flex: 1;
}

.channel-icon {
  width: 32px;
  height: 32px;
  object-fit: contain;
  margin-right: 12px;
}

.channel-info {
  flex: 1;
}

.channel-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.channel-code {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.channel-status {
  margin-left: 8px;
}

.channel-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-state {
  flex: 1;
  padding: 24px;
}

.channel-detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
  overflow: hidden;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.channel-title {
  display: flex;
  align-items: center;
}

.channel-title .channel-icon {
  width: 48px;
  height: 48px;
  margin-right: 16px;
}

.channel-title h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  color: #333;
}

.channel-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.detail-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.channel-status-control {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f6f8fa;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
}

.fixed-save-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.config-form-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
}

.config-form-container::-webkit-scrollbar {
  width: 6px;
}

.config-form-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.config-form-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.config-form-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .channel-config-workspace {
    flex-direction: column;
    height: auto;
  }

  .channel-sidebar {
    width: 100%;
    max-height: 300px;
  }

  .channel-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 8px;
  }

  .channel-item {
    margin-bottom: 0;
  }
}

@media (max-width: 768px) {
  .channel-item-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>